//
//  LoginViewController.m
//  ExhibitionHall
//
//  Created by 王洋 on 2019/5/27.
//  Copyright © 2019 王洋. All rights reserved.
//

#import "LoginViewController.h"
#import "MainViewController.h"
#import <WechatAuthSDK.h>
#import "TTWeChatManager.h"
#import "LoginRequestModel.h"

@interface LoginViewController ()<WechatAuthAPIDelegate>

@property (nonatomic, strong) UIImageView *backgroundImage;


@property (nonatomic, strong) UIView *cardView;

@property (nonatomic, strong) UIButton *WechatLoginBtn;
@property (nonatomic, strong) UIButton *accountLoginBtn;


@property (nonatomic, strong) UIView *WechatLoginView;
@property (nonatomic, strong) UIView *accountLoginView;

@property (nonatomic, strong) UIImageView *wxQRCode;
@property (nonatomic, strong) UILabel     *wxCodeStatusLab;
@property (nonatomic, strong) WechatAuthSDK *authSDK;

@property (nonatomic, strong) UITextField *phoneTextField;
@property (nonatomic, strong) UITextField *passwordTextField;

@property (nonatomic, strong) LoginRequestModel *requestModel;

@property (nonatomic, strong) UIButton *loginButton;



@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.phoneTextField.text = @"admin";
    self.passwordTextField.text = @"admin@1233";

    
    [self initView];
    
    WEAKSELF
    [TTWeChatManager getWechatSignatureComplete:^(NSString * _Nonnull signStr, NSString * _Nonnull timeStr) {
        
        [weakSelf.authSDK Auth:TT_wxAppID nonceStr:timeStr timeStamp:timeStr scope:@"snsapi_userinfo," signature:signStr schemeData:nil];
    }];

}

- (void)initView {
    
    [self.view addSubview:self.backgroundImage];
    [self.backgroundImage addSubview:self.cardView];
    
    [self.cardView addSubview:self.WechatLoginBtn];
    [self.cardView addSubview:self.accountLoginBtn];
    [self.cardView addSubview:self.WechatLoginView];
    [self.cardView addSubview:self.accountLoginView];
    
    [self.view addSubview:self.loginButton];
    [self.accountLoginView addSubview:self.phoneTextField];
    [self.accountLoginView addSubview:self.passwordTextField];
    
    [self.WechatLoginView addSubview:self.wxQRCode];
    [self.WechatLoginView addSubview:self.wxCodeStatusLab];

    [self.backgroundImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_equalTo(self.view);
    }];
    
    [self.cardView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.backgroundImage);
        make.centerY.mas_equalTo(self.backgroundImage);
        make.width.mas_equalTo(TTScreenWidth * 0.5);
        make.height.mas_equalTo(TTScreenWidth * 0.5*0.8);
    }];
    
    [self.loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.cardView);
        make.top.mas_equalTo(self.cardView.mas_bottom).offset(2);
        make.height.mas_equalTo(TTScreenWidth * 0.08 - 2);
    }];
    
    [self.WechatLoginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_equalTo(self.cardView);
        make.height.mas_equalTo(TTScreenWidth * 0.08);
        make.width.mas_equalTo(TTScreenWidth * 0.25);
    }];
    
    [self.accountLoginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.top.mas_equalTo(self.cardView);
        make.height.mas_equalTo(TTScreenWidth * 0.08);
        make.width.mas_equalTo(TTScreenWidth * 0.25);
    }];
    
    [self.WechatLoginView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(self.cardView);
        make.top.mas_equalTo(self.WechatLoginBtn.mas_bottom);
    }];
    
    [self.accountLoginView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(self.cardView);
        make.top.mas_equalTo(self.accountLoginBtn.mas_bottom);
    }];
    
    [self.phoneTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.accountLoginView);
        make.height.mas_equalTo(TTScreenWidth * 0.06);
        make.width.mas_equalTo(TTScreenWidth * 0.4);
        make.top.mas_equalTo(TTScreenWidth * 0.08);
    }];
    
    [self.passwordTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.accountLoginView);
        make.height.mas_equalTo(TTScreenWidth * 0.06);
        make.width.mas_equalTo(TTScreenWidth * 0.4);
        make.top.mas_equalTo(self.phoneTextField.mas_bottom).offset(20);
    }];
    
    [self.wxQRCode mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.centerY.mas_equalTo(0);
        make.width.mas_equalTo(150);
        make.height.mas_equalTo(150);
    }];
    
    [self.wxCodeStatusLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.wxQRCode);
        make.width.mas_equalTo(150);
        make.top.mas_equalTo(self.wxQRCode.mas_bottom).offset(10);
    }];
    
    
    [self WeChatLoginShow];

}

#pragma mark 微信扫码回调
-(void)onAuthGotQrcode:(UIImage *)image {
    self.wxQRCode.image = image;
    _wxCodeStatusLab.text = @"请使用微信扫码登录";
}

-(void)onAuthFinish:(int)errCode AuthCode:(NSString *)authCode {
    
    /*
     WechatAuth_Err_Ok = 0,  //Auth成功
     WechatAuth_Err_NormalErr = -1,  //普通错误
     WechatAuth_Err_NetworkErr = -2, //网络错误
     WechatAuth_Err_GetQrcodeFailed = -3,    //获取二维码失败
     WechatAuth_Err_Cancel = -4,     //用户取消授权
     WechatAuth_Err_Timeout = -5,    //超时
     */
    switch (errCode) {
        case WechatAuth_Err_Ok:{//成功
            self.requestModel.AuthCode = authCode;
            [self requestTokenWithModel:self.requestModel isAuth:YES];
        }break;
        case WechatAuth_Err_NormalErr:{//普通错误
            self.wxCodeStatusLab.text = @"普通错误";

        }break;
        case WechatAuth_Err_NetworkErr:{//网络错误
            self.wxCodeStatusLab.text = @"网络错误";

        }break;
        case WechatAuth_Err_GetQrcodeFailed:{//获取二维码失败
            self.wxCodeStatusLab.text = @"获取二维码失败";

        }break;
        case WechatAuth_Err_Cancel:{//用户取消授权
            self.wxCodeStatusLab.text = @"用户取消授权";

        }break;
        case WechatAuth_Err_Timeout:{//超时
            
            self.wxCodeStatusLab.text = @"二维码超时";
        }break;
            
        default:
            break;
    }

    WEAKSELF
    [TTWeChatManager getWechatSignatureComplete:^(NSString * _Nonnull signStr, NSString * _Nonnull timeStr) {
        
        [weakSelf.authSDK Auth:TT_wxAppID nonceStr:timeStr timeStamp:timeStr scope:@"snsapi_userinfo," signature:signStr schemeData:nil];
    }];
}

- (void)doLogin:(UIButton *)button {
    
    [self requestTokenWithModel:nil isAuth:NO];
}

- (void)requestTokenWithModel:(LoginRequestModel *)model isAuth:(BOOL)isAuth {
    
    NSMutableDictionary *param = [NSMutableDictionary new];

    if (isAuth) {
        [param setValue:model.AuthCode?:@"" forKey:@"username"];
        [param setValue:@"AHV8epuzfu" forKey:@"companyKey"];

    } else {
        [param setValue:self.phoneTextField.text?:@"" forKey:@"username"];
        [param setValue:self.passwordTextField.text?:@"" forKey:@"password"];
        [param setValue:@"AHV8epuzfu" forKey:@"companyKey"];
    }

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_LOGIN_API];
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:param FinishBlock:^(id  _Nonnull data) {

        BOOL fail = [[data valueForKey:@"code"] boolValue];
        NSDictionary *resultDic = [data valueForKey:@"data"];
        if (!fail) {
            NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
            [userDefault setValue:[resultDic valueForKey:@"name"] forKey:@"uer_name"];
            [userDefault setValue:[resultDic valueForKey:@"icon"] forKey:@"user_icon"];
            [userDefault setValue:[resultDic valueForKey:@"accessToken"] forKey:@"access_token"];
            [userDefault synchronize];
            [weakSelf goMainVC];
            [WHToast showSuccessWithMessage:@"登录成功" duration:TT_GLOBAL_DURATION_TIME finishHandler:^{
                
            }];
        } else {
            
            [WHToast showErrorWithMessage:[data valueForKey:@"message"] duration:2 finishHandler:^{
            
            }];
        }
        
        //存储用户信息
    } FailedBlock:^(NSError * _Nonnull error) {

        [WHToast showErrorWithMessage:@"其他失败" duration:TT_GLOBAL_DURATION_TIME finishHandler:^{
            
        }];
    }];
    
//            [self goMainVC];

    
}

- (void)goMainVC {
    
    UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:[MainViewController new]];
    [UIApplication sharedApplication].keyWindow.rootViewController = navController;
    navController.navigationBar.hidden = YES;
}


- (void)WeChatLoginShow {
    
    self.WechatLoginView.hidden = NO;
    self.accountLoginView.hidden = YES;
    self.loginButton.hidden = YES;
    
    [self.WechatLoginBtn setTitle:@"微信扫码登录中" forState:UIControlStateNormal];
    [self.accountLoginBtn setTitle:@"账号" forState:UIControlStateNormal];
}

- (void)accountLoginShow {
    self.WechatLoginView.hidden = YES;
    self.accountLoginView.hidden = NO;
    self.loginButton.hidden = NO;
    
    [self.WechatLoginBtn setTitle:@"微信" forState:UIControlStateNormal];
    [self.accountLoginBtn setTitle:@"账号密码登录中" forState:UIControlStateNormal];
}

- (void)changeLoginType:(UIButton *)btn {
    switch (btn.tag) {
        case 0:{//微信
            [self WeChatLoginShow];
                }break;
        case 1:{//账号
            [self accountLoginShow];
                }break;
        default:
            break;
    }
    
}

-(WechatAuthSDK *)authSDK {
    if (!_authSDK) {
        _authSDK = [[WechatAuthSDK alloc] init];
        _authSDK.delegate = self;
    }
    return _authSDK;
}


-(UIImageView *)wxQRCode {
    if (!_wxQRCode) {
        _wxQRCode = [[UIImageView alloc] init];
        _wxQRCode.backgroundColor = [UIColor clearColor];
    }
    return _wxQRCode;
}

- (UILabel *)wxCodeStatusLab {
    if (!_wxCodeStatusLab) {
        _wxCodeStatusLab = [[UILabel alloc] init];
        _wxCodeStatusLab.textAlignment = NSTextAlignmentCenter;
        _wxCodeStatusLab.font = [UIFont systemFontOfSize:16];
        _wxCodeStatusLab.text = @"请使用微信扫码登录";
    }
    return _wxCodeStatusLab;
}

- (UIImageView *)backgroundImage {
    if (!_backgroundImage) {
        _backgroundImage = [[UIImageView alloc] init];
        _backgroundImage.userInteractionEnabled = YES;
        _backgroundImage.contentMode = UIViewContentModeScaleAspectFill;
        [_backgroundImage sd_setImageWithURL:[NSURL URLWithString:@"http://file06.16sucai.com/2016/0507/8e79ee5bc3d1669833c42cc224e7ac84.jpg"]];
    }
    return _backgroundImage;
}


-(UIView *)cardView {
    if (!_cardView) {
        _cardView = [[UIView alloc] init];
        _cardView.backgroundColor = [UIColor whiteColor];
        _cardView.userInteractionEnabled = YES;
        _cardView.layer.cornerRadius = 10;
        _cardView.layer.masksToBounds = YES;
        
    }
    return _cardView;
}


- (UIButton *)loginButton {
    if (!_loginButton) {
        _loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _loginButton.backgroundColor = UIColorHex(#3296FA);
        _loginButton.layer.cornerRadius = 10;

        [_loginButton setTitle:@"进入商城" forState:UIControlStateNormal];

        [_loginButton addTarget:self action:@selector(doLogin:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginButton;
}

-(UIButton *)WechatLoginBtn {
    
    if (!_WechatLoginBtn) {
        _WechatLoginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_WechatLoginBtn setTitle:@"微信扫码登录" forState:UIControlStateNormal];
        _WechatLoginBtn.titleLabel.font = [UIFont systemFontOfSize:20];
        [_WechatLoginBtn setTitleColor:UIColorHex(#FFFFFF) forState:UIControlStateNormal];
        [_WechatLoginBtn setBackgroundColor:UIColorHex(#89DE4D)];
        _WechatLoginBtn.tag = 0;
        [_WechatLoginBtn addTarget:self action:@selector(changeLoginType:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _WechatLoginBtn;
}

-(UIButton *)accountLoginBtn {
    
    if (!_accountLoginBtn) {
        _accountLoginBtn  =[UIButton buttonWithType:UIButtonTypeCustom];
        [_accountLoginBtn setTitle:@"账号密码登录" forState:UIControlStateNormal];
        _accountLoginBtn.titleLabel.font = [UIFont systemFontOfSize:20];
        [_accountLoginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_accountLoginBtn setBackgroundColor:UIColorHex(#3296FA)];
        _accountLoginBtn.tag = 1;
        [_accountLoginBtn addTarget:self action:@selector(changeLoginType:) forControlEvents:UIControlEventTouchUpInside];

    }
    return _accountLoginBtn;
}

-(UIView *)WechatLoginView {
    
    if (!_WechatLoginView) {
        _WechatLoginView = [[UIView alloc] init];
    }
    return _WechatLoginView;
}

-(UIView *)accountLoginView {
    if (!_accountLoginView) {
        _accountLoginView = [[UIView alloc] init];
    }
    return _accountLoginView;
}

-(UITextField *)phoneTextField {
    if (!_phoneTextField) {
        _phoneTextField = [[UITextField alloc] init];
        _phoneTextField.placeholder = @"请输入手机号码";
        _phoneTextField.layer.borderWidth = 1.0f;
        _phoneTextField.font = [UIFont systemFontOfSize:28];
        _phoneTextField.layer.borderColor = UIColorHex(#f1f1f1).CGColor;
        _phoneTextField.layer.cornerRadius = 10;
    }
    return _phoneTextField;
}

-(UITextField *)passwordTextField {
    if (!_passwordTextField) {
        _passwordTextField = [[UITextField alloc] init];
        _passwordTextField.placeholder = @"请输入登录密码";
        _passwordTextField.layer.borderWidth = 1.0f;
        _passwordTextField.font = [UIFont systemFontOfSize:28];
        _passwordTextField.layer.borderColor = UIColorHex(#f1f1f1).CGColor;
        _passwordTextField.layer.cornerRadius = 10;
    }
    return _passwordTextField;
}

- (LoginRequestModel *)requestModel {
    if (!_requestModel) {
        _requestModel = [[LoginRequestModel alloc] init];
    }
    return _requestModel;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
